/**
 * Copyright(c)2013 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.utils;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import com.pmc.dwa.common.exception.PmcRuntimeException;
import com.pmc.dwa.security.intercept.PmcSecurityMetadataSource;

/**
 * @description 自定义权限标签
 * @author aokunsang
 * @date 2013-7-8
 */
public class PmcSecurityTag extends TagSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String label;
	
	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException {
		String url = strip(((HttpServletRequest)pageContext.getRequest()).getServletPath());
		if(StringUtils.isEmpty(url)) throw new PmcRuntimeException("使用pmcSecurity标签时，url不能为空值。");
		Map<String,Collection<ConfigAttribute>> allResources = PmcSecurityMetadataSource.getAllResources();
		//用户所有的权限
		Collection<SimpleGrantedAuthority> auths = (Collection<SimpleGrantedAuthority>)SpringSecurityUtils.getAuthentication().getAuthorities();
		Collection<ConfigAttribute> allAuths= allResources.get(url);
		if(allAuths==null){
			System.out.println(String.format("你所请求的URL地址在资源库中没有查询到，请确认URL[%s]的有效性。", url));
			return EVAL_BODY_INCLUDE;  //数据库中不存在该URL地址
		}
		Iterator<ConfigAttribute> iter = allAuths.iterator();
		while(iter.hasNext()){
			String needRole = iter.next().getAttribute();
			for(GrantedAuthority ga:auths){
				if(needRole.equals(ga.getAuthority())){
					return EVAL_BODY_INCLUDE;
				}
			}
		}
		return SKIP_BODY;
	}
	
	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}
	/**
	 * 格式化URL路径
	 * @param path
	 * @return
	 */
    private String strip(String path) {
        if (path == null) {
            return null;
        }

        int scIndex = path.indexOf("/pages");
        int suffixIndex = path.indexOf(".jsp");
        if (scIndex < 0) {
           return path;
        }
        if(suffixIndex < 0){
        	suffixIndex = path.length();
        }
        return "/jsp"+path.substring(scIndex + 6, suffixIndex)+"/"+label;
    }

	/**
	 * @return the label
	 */
	public String getLabel() {
		return label;
	}

	/**
	 * @param label the label to set
	 */
	public void setLabel(String label) {
		this.label = label;
	}
}
